function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function parseJSON(response) {
  return response.json();
}

function checkResponse(response) {
  if (response.success) {
    return response.data;
  }
  const error = new Error(response.message);
  error.message = response.message;
  throw error;
}


const api = {
  getRequest(url, args) {
    return fetch(url, {
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: args,
    }).then(checkStatus)
      .then(parseJSON)
      .then(checkResponse);
  },
  postRequest(url, data) {
    return fetch(url, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin',
      body: JSON.stringify(data),
    }).then(checkStatus)
      .then(parseJSON)
      .then(checkResponse);
  },
  putRequest(url, data) {
    return fetch(url, {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin',
      body: JSON.stringify(data),
    }).then(checkStatus)
      .then(parseJSON)
      .then(checkResponse);
  },
  deleteRequest(url, data) {
    return fetch(url, {
      method: 'DELETE',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin',
      body: JSON.stringify(data),
    }).then(checkStatus)
      .then(parseJSON)
      .then(checkResponse);
  },
};

api.getMenu = function getMenu() {
  return api.getRequest('/api/admin/menu');
};

export default api;
